using Godot;
using System.Collections.Generic;

public partial class DialogueUI : CanvasLayer
{
    [Signal] public delegate void DialogueEventEventHandler(string eventName); // 供外部监听

    [Export] public double DefaultCharDelay = 0.05; // 默认打字速度
    [Export] public double DefaultReadDelay = 2.0;  // 默认阅读等待

    public string CurrentDialogueId { get; private set; } = "";

    // 内部引用
    private RichTextLabel _label;
    private Panel _panel;
    private AudioStreamPlayer _audio;
    private Timer _typingTimer;
    private Timer _autoNextTimer;

    private Queue<DialogueLine> _linesQueue = new Queue<DialogueLine>();
    private bool _isTyping = false;

    // 当前正在处理的行数据
    private DialogueLine _currentLine;

    public struct DialogueLine
    {
        public string Name;
        public string Content;
        public string ColorHex;
        public float TypingSpeed;  // -1 使用默认
        public string SignalEvent; // 空字符串不触发
        public float WaitTime;     // -1 使用默认
    }

    public override void _Ready()
    {
        // ... 获取节点引用保持不变 ...
        _label = GetNode<RichTextLabel>("Control/Panel/RichTextLabel");
        _panel = GetNode<Panel>("Control/Panel");
        _audio = GetNode<AudioStreamPlayer>("AudioStreamPlayer");
        _typingTimer = GetNode<Timer>("TypingTimer");
        _autoNextTimer = GetNode<Timer>("AutoNextTimer");

        _panel.Visible = false;

        _typingTimer.Timeout += OnTypeChar;
        _autoNextTimer.Timeout += OnNextLine;
    }

    public void ShowDialogue(List<DialogueLine> lines, string dialogueId)
    {
        if (_panel.Visible && CurrentDialogueId == dialogueId) return;

        CurrentDialogueId = dialogueId;
        _linesQueue.Clear();
        foreach (var line in lines) _linesQueue.Enqueue(line);

        if (_linesQueue.Count > 0)
        {
            _panel.Visible = true;
            StartNextLine();
        }
    }

    private void StartNextLine()
    {
        if (_linesQueue.Count == 0)
        {
            CloseDialogue();
            return;
        }

        _currentLine = _linesQueue.Dequeue();

        // 1. 处理事件 (在对话开始时触发)
        if (!string.IsNullOrEmpty(_currentLine.SignalEvent))
        {
            EmitSignal(SignalName.DialogueEvent, _currentLine.SignalEvent);
            GD.Print($"[Dialogue] 触发事件: {_currentLine.SignalEvent}");
            // 例如: 如果事件是 ShakeCamera，可以在全局通过连接这个信号来处理
        }

        // 2. 设置文本和颜色
        // 如果有名字，你可以选择加粗显示名字，或者在另一个Label显示
        string finalContent = _currentLine.Content;
        if (!string.IsNullOrEmpty(_currentLine.Name))
        {
            // 可选：把名字加在前面加粗显示
            // finalContent = $"[b]{_currentLine.Name}:[/b] {finalContent}";
        }

        _label.Text = $"[color={_currentLine.ColorHex}]{finalContent}[/color]";
        _label.VisibleCharacters = 0;

        // 3. 设置打字速度 (支持单句变速)
        double speed = _currentLine.TypingSpeed > 0 ? _currentLine.TypingSpeed : DefaultCharDelay;

        _isTyping = true;
        _typingTimer.WaitTime = speed;
        _typingTimer.Start();
    }

    private void OnTypeChar()
    {
        _label.VisibleCharacters++;

        // ... 音效逻辑保持不变 ...
        // ... 标点符号停顿逻辑保持不变 ...

        if (_label.VisibleRatio >= 1.0f)
        {
            FinishTyping();
        }
    }

    private void FinishTyping()
    {
        _isTyping = false;
        _typingTimer.Stop();

        // 4. 设置阅读等待时间 (支持单句自定义)
        double wait = _currentLine.WaitTime > 0 ? _currentLine.WaitTime : DefaultReadDelay;

        _autoNextTimer.WaitTime = wait;
        _autoNextTimer.Start();
    }

    private void OnNextLine()
    {
        _autoNextTimer.Stop();
        StartNextLine();
    }

    private void CloseDialogue()
    {
        _panel.Visible = false;
        CurrentDialogueId = "";
        EmitSignal(SignalName.DialogueEvent, "DialogueFinished"); // 触发结束事件
    }
}